<template>
  <div class="groups-tree">
    <a-input-group compact>
      <a-input-search allowClear placeholder="请输入名称搜索" @search="onSearch" />
      <a-button
        type="primary"
        icon="plus-circle"
        @click="addGroups()"
        v-show="!selectedKey"
        v-has="'grid:primary'"
        title="创建顶级网格"> 创建网格 </a-button>
      <a-button
        type="primary"
        icon="plus-circle"
        @click="addGroups()"
        v-show="selectedKey"
        v-has="'grid:subordinate'"
        title="创建下级网格"> 创建网格 </a-button>
    </a-input-group>
    <a-tree
      v-model="checkedKeys"
      show-line
      :auto-expand-parent="autoExpandParent"
      :expanded-keys="expandedKeys"
      :selected-keys="selectedKeys"
      :tree-data="treeData"
      @expand="onExpand"
      @select="onSelect"
      v-if="treeData.length>0"
      style="padding-left: 9px;"
    >
      <template slot="custom" slot-scope="item">
        <span> {{ item.title }}</span>
        <span v-if="item.key == selectedKey">
          <a-tooltip placement="topLeft" title="修改网格名称" v-has="'grid:edit'">
            <a-icon type="edit" @click.stop="editGroups(item)" style="padding-left:16px;" />
          </a-tooltip>
          <a-tooltip placement="topLeft" title="删除网格" v-has="'grid:delete'">
            <a-icon type="delete" @click.stop="deleteGroups(item)" style="padding-left:16px;" />
          </a-tooltip>
        </span>
      </template>
    </a-tree>
    <a-empty :image="simpleImage" v-else style="padding-top:60px;">
      <span slot="description"> 还未创建网格</span>
    </a-empty>
    <groups-handle-modal :title="groupsModalTitle" @ok="finish" ref="groupsModalRef" />
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue'
import groupsHandleModal from './groupsHandleModal'
import * as structureApi from '@/api/xlgc/structure.js'
var setSlot = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    arr[i].scopedSlots = {
      title: 'custom'
    }
    arr[i].childrenKeys = getChild(arr, arr[i].key, []) // 获取某节点的所有子节点（包含当前key至所有children的key值）
    if (arr[i].children && arr[i].children.length > 0) {
      setSlot(arr[i].children)
    }
  }
  return arr
}
var getChild = (nodes, item, arr) => {
  for (let el of nodes) {
    if (el.key === item) {
      arr.push(el.key)
      if (el.children) {
        childNodesDeep(el.children, arr)
      }
    } else if (el.children) {
      getChild(el.children, item, arr)
    }
  }
  return arr
}
var childNodesDeep = (nodes, arr) => {
  if (nodes) {
 nodes.forEach((ele) => {
    arr.push(ele.key)
    if (ele.children) {
      childNodesDeep(ele.children, arr)
    }
  })
}
}
export default {
  name: 'GroupsTree',
  components: {
    groupsHandleModal
  },
  data() {
    return {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      groupsModalTitle: null
    }
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
  },
  created() {
    this.initTree()
  },
  computed: {
    selectedKey() {
      if (this.selectedKeys.length > 0) {
        return this.selectedKeys[0]
      } else {
        return null
      }
    }
  },
  watch: {
    checkedKeys(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.$emit('checkedKeys', checkedKeys)
    }
  },
  methods: {
    initTree(departName) {
      let obj = { departName: departName }
      structureApi.searchWG(obj).then(res => {
        if (res.success) {
          let datas = res.result
          // this.treeData = setSlot(this.treeData)
          this.treeData = setSlot(datas)
          this.$emit('tree', this.treeData)
          for (let i = 0; i < this.treeData.length; i++) {
            let temp = this.treeData[i]
            this.setThisExpandedKeys(temp)
          }
        }
      })
    },
    onSearch(value) {
      this.initTree(value)
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.expandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
      this.$emit('checkedKeys', checkedKeys)
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
      this.$emit('selectedKeys', selectedKeys)
    },
    // 新建网格、新建下级网格
    addGroups() {
      if (this.selectedKey) {
        const dataRef = { value: this.selectedKey }
        this.groupsModalTitle = '新建下级网格'
        this.$refs.groupsModalRef.add(dataRef)
      } else {
        this.groupsModalTitle = '创建网格'
        this.$refs.groupsModalRef.add()
      }
    },
    // 修改网格名称
    editGroups(item) {
      const { dataRef } = item
      this.groupsModalTitle = '修改网格名称'
      if (this.$refs && this.$refs.groupsModalRef) {
        this.$refs.groupsModalRef.edit(dataRef)
      }
    },
    // 删除网格
    deleteGroups(item) {
      let that = this
      const { dataRef } = item
      const obj = { id: dataRef.key }
      that.$confirm({
        title: `确定删除“${dataRef.title}”?`,
        okType: 'danger',
        onOk() {
          structureApi.deleteWG(obj).then(res => {
            if (res.success) {
              that.$message.success(res.message ? res.message : '操作成功！')
              that.finish('delete')
            } else {
              that.$message.warn(res.message ? res.message : '操作失败！')
            }
          }).catch(e => {
            that.$message.warn('操作失败！')
          })
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    finish(type) {
      this.initTree()
      if (type == 'delete') {
        this.$emit('selectedKeys', [])
      } else if (type == 'edit') {
        this.$emit('selectedKeys', this.selectedKeys)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.groups-tree {
  padding-bottom: 10px;
  min-height: 600px;
}
/deep/.ant-input-group {
  margin: 24px auto 14px;
  width: 92%;
  display: flex;
  .ant-btn {
    width: 34%;
    margin-left: 10px;
    padding-left: 6px;
    padding-right: 6px;
    margin-right: 0 !important;
    border-right-width: 1px !important;
    border-top-right-radius: 4px !important;
    border-bottom-right-radius: 4px !important;
  }
}
</style>
